package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mongo.MovementApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.CommentType;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.exception.ErrorResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommentsService {
    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 分页查询评论列表
     *
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = list.stream()
                .map(item -> item.getUserId())
                .collect(Collectors.toList());
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
//        list.stream().map((comment)->{
//            UserInfo userInfo = map.get(comment.getUserId());
//            if(userInfo!=null){
//             return CommentVo.init(userInfo,comment);
//            }
//        }).collect(Collectors.toList());
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {

            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                List<Integer> comment1 = commentApi.getComment(comment.getId(), comment.getUserId());
                for (Integer integer : comment1) {
                    if(integer==1){
                    vo.setHasLiked(1);
                    }
                }
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page, pagesize, 0, vos);
    }

    /**
     * 发布评论
     *
     * @param movementId
     * @param comment
     */
    public void saveComments(String movementId, String comment) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment1);
        log.info("commentCount = " + commentCount);
    }

    /**
     * 点赞
     *
     * @param movementId
     * @return
     */
    public Integer likeComment(String movementId) {
        //1、调用API查询用户是否已点赞
        //获取当前用户
        Boolean aboolean = commentApi.findCommentByUserId(UserHolder.getUserId(),movementId,CommentType.LIKE);
        //2、如果已经点赞，抛出异常
        if (aboolean) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3、调用API保存数据到Mongodb
        Comment comment=new Comment();
        //设置id
        comment.setPublishId(new ObjectId(movementId));
        //设置当前评论为点赞
        comment.setCommentType(CommentType.LIKE.getType());
        //设置点赞人id
        comment.setUserId(UserHolder.getUserId());
        //设置被评论人id，通过动态id，获取当前动态详细信息，获取动态发布人id
        Movement movement = movementApi.findById(movementId);
        comment.setPublishUserId(movement.getUserId());
        //设置更新时间
        comment.setCreated(System.currentTimeMillis());
        Integer likeCount = movement.getLikeCount();
        //设置当前评论的点赞数,并获取到点赞总数
        comment.setLikeCount(likeCount);
        Integer count = commentApi.save(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    /**
     * 取消点赞
     *
     * @param movementId
     * @return
     */
    public Integer dislikeComment(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean aboolean = commentApi.findCommentByUserId( UserHolder.getUserId(),movementId,CommentType.LIKE);
        //2、如果还未点赞抛出异常信息
        if(!aboolean){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API删除点赞信息返回点赞数量
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count= commentApi.remove(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    /**
     * 喜欢
     * @param movementId
     * @return
     */
    public Integer loveComment(String movementId) {
        //1、调用API查询用户是否已喜欢
        Boolean aboolean = commentApi.findCommentByUserId( UserHolder.getUserId(),movementId,CommentType.LOVE);
        //2、如果还未喜欢抛出异常信息
        if(aboolean){
            throw new BusinessException(ErrorResult.loveError());
        }
        //3、调用API删除点赞信息返回点赞数量
        //3、调用API保存数据到Mongodb
        Comment comment=new Comment();
        //设置id
        comment.setPublishId(new ObjectId(movementId));
        //设置当前评论为点赞
        comment.setCommentType(CommentType.LOVE.getType());
        //设置点赞人id
        comment.setUserId(UserHolder.getUserId());
        //设置被评论人id，通过动态id，获取当前动态详细信息，获取动态发布人id
        Movement movement = movementApi.findById(movementId);
        comment.setPublishUserId(movement.getUserId());
        //设置更新时间
        comment.setCreated(System.currentTimeMillis());
        Integer likeCount = movement.getLikeCount();
        //设置当前评论的点赞数,并获取到点赞总数
        comment.setLikeCount(likeCount);
        Integer count = commentApi.save(comment);
        //4、拼接redis的key，将用户的喜欢状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    /**
     * 取消喜欢
     * @param movementId
     * @return
     */
    public Integer disloveComment(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean aboolean = commentApi.findCommentByUserId( UserHolder.getUserId(),movementId,CommentType.LOVE);
        //2、如果还未点赞抛出异常信息
        if(!aboolean){
            throw new BusinessException(ErrorResult.disloveError());
        }
        //3、调用API删除点赞信息返回点赞数量
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count= commentApi.remove(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    /**
     * 评论点赞
     * @param commentId
     * @return
     */
    public Integer commentLike(String commentId) {
        //根据被点赞的评论的id查询当前评论的详细信息
        boolean commentByUserId = commentApi.findCommentByUserId(UserHolder.getUserId(), commentId, CommentType.LIKE);
        //没有被点赞抛出异常
        if(commentByUserId){
            throw new BusinessException(ErrorResult.likeError());
        }
        //封装点赞信息
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(commentId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        //根据当前评论id获取评论人id
        Comment commentAA = commentApi.getCommentByUserId(commentId);
        comment.setPublishUserId(commentAA.getUserId());
        //保存评论信息
        Integer count = commentApi.saveComment(comment);
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    /**
     * 评论取消点赞
     * @param commentId
     * @return
     */                                  //评论id
    public Integer commentDisLike(String commentId) {
        //根据被点赞的评论的id查询当前点赞的详细信息
        boolean commentByUserId = commentApi.findCommentByUserId(UserHolder.getUserId(), commentId, CommentType.LIKE);
        //未点赞抛出异常
        if(!commentByUserId){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //删除评论点赞信息
        Integer count = commentApi.removeComment(UserHolder.getUserId(),commentId);
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}
